<template>
    <el-main v-loading="loading">
        <div class="margin_bottom_30">
            <el-button
                :type="activeIndex === index ? 'primary' : 'default'"
                size="small"
                @click="handleActive(item, index)"
                v-for="(item, index) of ordersStateList"
                :key="index">{{item.name}}({{item.count}})</el-button>
            <el-button
                type="primary"
                style="margin-left: 30px"
                size="small"
                @click="handleBulkShipment">批量发货</el-button>
        </div>
        <el-row :gutter="20" class="margin_bottom_30" type="flex">
            <el-col :span="3">
                <el-input placeholder="订单编号" size="small" v-model="filterData.tradeNo"></el-input>
            </el-col>
             <el-col :span="3">
                <el-input placeholder="收货人姓名/手机号码" size="small" v-model="filterData.sendNameOrReceiveNameOrPhone"></el-input>
            </el-col>
            <el-col :span="5">
                <el-date-picker
                    size="small"
                    v-model="timeRange"
                    type="daterange"
                    unlink-panels
                    style="width:100%"
                    range-separator="-"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    @change="checkTimeChange"
                ></el-date-picker>
            </el-col>
            <el-col :span="3" :push="1">
                <p style="display: flex">
                    <el-button type="primary" size="small" @click="search">搜 索</el-button>
                    <el-button size="small" @click="resetQuery">重 置</el-button>
                </p>
            </el-col>
        </el-row>
        <el-table
            :data="dataList"
            border
            :row-key="row => row.orderUid"
            height="580"
            :header-cell-style="{background:'#afafaf',color:'#606266'}"
            ref="multipleTable"
            @selection-change="handleSelectionChange"
        >
            <el-table-column align="center" type="selection" reserve-selection width="40"></el-table-column>
            <el-table-column prop="tradeNo" width="180" label="订单编号"></el-table-column>
            <el-table-column prop="payTime" width="160" label="支付时间">
                <template slot-scope="scope">{{scope.row.payTime || '--'}}</template>
            </el-table-column>
            <el-table-column prop="memberNickName" width="150" label="发送方">
                <template slot-scope="scope">{{scope.row.memberNickName && $util.decode(scope.row.memberNickName)}}</template>
            </el-table-column>
            <el-table-column prop="receiveNickName" width="150" label="接收方">
                <template slot-scope="scope">{{scope.row.receiveNickName && $util.decode(scope.row.receiveNickName)}}</template>
            </el-table-column>
            <el-table-column width="200" label="商品信息">
                <template slot-scope="scope">
                    <el-tooltip :content="item.productName" v-for="item of scope.row.itemModels" :key="item.itemUid">
                        <p>{{item.productName | controlLength}} x{{item.buyCount}}</p>
                    </el-tooltip>
                </template>
            </el-table-column>
            <el-table-column label="收货地址" width="200">
                <template slot-scope="scope">
                    <template v-if="scope.row.address">
                        <p>地址：{{scope.row.address}}</p>
                        <p>电话：{{scope.row.mobile}}</p>
                        <p>联系人：{{scope.row.receiveNickName && $util.decode(scope.row.receiveNickName)}}</p>
                    </template>
                    <span v-else>待填写地址</span>
                </template>
            </el-table-column>
            <el-table-column width="100" label="订单金额">
                <template slot-scope="scope">
                    <span class="text-price" v-if="scope.row.realAmount">{{$util.prices(scope.row.realAmount)}}</span>
                    <span v-else>--</span>
                </template>
            </el-table-column>
            <el-table-column prop="payType" width="100" label="支付方式">
                <template slot-scope="scope">
                     <span>{{getOrderpayType(scope.row.payType)}}</span>
                </template>
            </el-table-column>
            <el-table-column width="100" label="订单状态">
                <template slot-scope="scope">
                    <span>{{getOrderStatus(scope.row.status)}}</span>
                </template>
            </el-table-column>
            <el-table-column prop="payTime" width="160" label="创建时间">
                <template slot-scope="scope">{{scope.row.createTime || '--'}}</template>
            </el-table-column>
            <el-table-column align="center"  label="操作" width="150" fixed="right">
                <template slot-scope="scope">
                    <el-button type="text" @click="handlePreView(scope.row)" size="small">查看订单</el-button>
                    <el-button type="text" v-if="scope.row.status === 0" @click="handleUpdateOrder(scope.row, 'close')" size="small">关闭订单</el-button>
                    <el-button type="text" v-if="scope.row.status === 1" @click="handleShip(scope.row)" size="small">订单发货</el-button>
                    <el-button v-if="scope.row.status === 2" type="text" @click="handleLogistics(scope.row)" size="small">查看物流</el-button>
                    <el-button v-if="scope.row.status === 2" type="text" @click="handleShip(scope.row)" size="small">修改物流单号</el-button>
                </template>
            </el-table-column>
        </el-table>

        <el-row class="footer">
            <el-col :span="12">
				<el-checkbox
                    v-model="checkAll"
                    :disabled="!dataList.length"
                    @change="handleCheckAllChange">全选
                </el-checkbox>
			</el-col>
			<el-col :span="12">
				<el-pagination
                    @current-change="handlePaginationChange"
                    :current-page="page"
                    :page-size="10"
                    background
                    :disabled="!dataList.length"
                    :total="count"
                    class="text_align_right"
                    layout="total, prev, pager, next, jumper">
                </el-pagination>
			</el-col>
		</el-row>
		<el-drawer
			size="80%"
			destroy-on-close
            @close="handleClose"
			:visible.sync="openPreviewPage">
				<orders-preview
                    ref="preview"
                    :transData="templateInfo"
                    :ordersStateList="ordersStateList"
                    @ClosePreviewPage="handleClose">
                </orders-preview>
		</el-drawer>

		<el-drawer
            @close="handleCloseAction"
            :visible.sync="showShipPage"
            :title="shipList.length > 1 ? '批量发货' : '订单发货'"
            destroy-on-close size="80%">
			<orders-action
                ref="templateRef"
                :logisticsList="logisticsList"
                :infoData="shipList"
                @func="closeTemplatePage">
            </orders-action>
		</el-drawer>
        <!-- 物流 -->
        <el-drawer
            :visible.sync="showLogisticsPage"
            title="查看物流"
            @close="closeLogisticsPage"
            destroy-on-close size="60%">
			<logistics
                :orderUid="templateInfo.orderUid"
                :CourierCompany="logisticsList">
            </logistics>
		</el-drawer>
    </el-main>
</template>
<script>
    import ordersAction from './orders/action.vue';
    import logistics from './orders/logistics.vue';
    import ordersPreview from './orders/preview.vue';
    import {
        ordersList,
        updateOrdersStatus,
        trackingCompanyList
    } from "@/api/table";
    import utils from '@/utils/utils';

    export default {
        name: "ORDERS_LIST",
        filters: {
            controlLength: curStr => utils.controlLength(curStr, 10),
        },
        data() {
            return {
                activeIndex: 0,
                ordersStateList: [{
                    name: '全部订单',
                    count: 0,
                    status: ''
                }, {
                    name: '待支付',
                    count: 0,
                    status: 0
                }, {
                    name: '待发货',
                    count: 0,
                    status: 1
                }, {
                    name: '已发货',
                    count: 0,
                    status: 2
                }, {
                    name: '已完成',
                    count: 0,
                    status: 3
                }, {
                    name: '已关闭',
                    count: 0,
                    status: 4
                }],
                filterData: {},
                timeRange: [],
                count: 0,
                showLogisticsPage: false, // 物流
                checkAll: false, // 全选
                openPreviewPage: false, // 预览
                shipList: [],
                dataList: [],
                loading: false,
                page: 1,
                campaignTemplateType: 1,
                campaignStyleOrContentDesc:'',
                templateInfo: {},
                logisticsList: [],
                showShipPage: false // 发货
            }
        },
        components: {
            logistics,
            ordersAction,
            ordersPreview
        },
        mounted() {
            this.getData();
            this.getTrackingCompany();
            this.$event.on('ShowShipPage', info => {
                this.handleShip(info)
            });
            // 物流
            this.$event.on('ShowLogisticsPage', info => {
                this.handleLogistics(info)
            });
        },
        destroyed() {
            this.$event.off('ShowShipPage');
            this.$event.off('ShowLogisticsPage');
        },
        methods: {
            // 获取快递公司
            getTrackingCompany() {
				trackingCompanyList().then(res => {
					if (res.data.isSuccessful === "Y") {
                        const { data } = res.data
                        this.logisticsList = data;
					}
				});
			},
            // 时间选择
            checkTimeChange(e) {
                const startTime = e[0];
                const endTime = e[1]
                this.filterData = {
                    ...this.filterData,
                    startTime,
                    endTime
                }
                this.getData()
            },
            // 批量发货
            handleBulkShipment() {
                this.showShipPage = true;
                this.shipList = this.dataList;
                // 同步数据
				this.$nextTick(() => {
					this.$refs.templateRef.updateData()
				})
            },
            // 顶部
            handleActive(data, index) {
                if (this.activeIndex === index) return
                this.activeIndex = index;
                this.filterData.status = data.status;
                this.getData()
            },
            // 搜索
            search() {
                this.getData();
            },
            // 分页
            handlePaginationChange(val) {
                this.page = val;
                this.getData();
            },
            // 全选
            handleCheckAllChange(val) {
                if (this.checkAll) {
                    this.$refs.multipleTable.toggleAllSelection();
                } else {
                    this.$refs.multipleTable.clearSelection();
                }
            },
            resetQuery() {
                this.filterData = {};
                this.timeRange = [];
                this.page = 1;
                this.getData();
            },
            handlePreView(info = {}) {
                this.templateInfo = info;
                this.openPreviewPage = true;
                // 同步数据
				this.$nextTick(() => {
					this.$refs.preview.updateData()
				})
			},
			handleClose() {
                this.templateInfo = {}
                this.openPreviewPage = false;
            },
            // 获取订单状态
            getOrderStatus(status) {
                const orderInfo = this.ordersStateList.find(item => item.status === status) || {}
                return !Object.keys(orderInfo).length ? '--' : orderInfo.name
            },
            // 
            getOrderpayType(type) {
                switch (type) {
                    case 1: return '微信'
                    case 2: return '余额'
                    default: return '待支付';
                }
            },
            handleCloseAction() {
                this.shipList = [];
            },
            closeTemplatePage(data) {
                this.showShipPage = data.action;
                this.handleCloseAction();
                if (data.refresh) {
                    this.getData()
                }
            },
            // 监听选择的内容
            handleSelectionChange(val) {
                //val 为选中数据的集合
                this.checkAll = this.dataList.length === val.length
            },
            // 获取数据
            getData() {
                this.loading = true
                ordersList({
                    ...this.filterData,
                    page: this.page - 1
                }).then(result => {
                    if (result.data.isSuccessful === "Y") {
                        // console.log(result)
                        const { count, 
                            orderList,
                            unDelivery,
                            finished,
                            deliverying,
                            refund,
                            created,
                            allDelivery } = result.data.data;
                        this.count = count;
                        let redPacketInfo = [];
						orderList.map(i => {
                            let redPacketInfo = [];
                            i.redPacketModels.map(item => {
                                redPacketInfo.push({
                                    buyCount: 1,
                                    productName: item.redPacketName || '红包',
                                    productListPath: item.redPacketCoverUrl,
                                    unitPrice: item.redPacketAmount,
                                    totalPrice: item.redPacketAmount
                                })
                                return item
                            });
                            i.itemModels = [...i.itemModels, ...redPacketInfo]
                        });
                        this.dataList  = orderList;
                        this.ordersStateList = [{
                            name: '全部订单',
                            count: allDelivery,
                            status: ''
                        }, {
                            name: '待支付',
                            count: created,
                            status: 0
                        }, {
                            name: '待发货',
                            count: unDelivery,
                            status: 1
                        }, {
                            name: '已发货',
                            count: deliverying,
                            status: 2
                        }, {
                            name: '已完成',
                            count: finished,
                            status: 3
                        }, {
                            name: '已关闭',
                            count: refund,
                            status: 4
                        }];
                    }
                }).catch(err => {})
                .finally(() => {
                    if (this.loading) {
                      this.loading = false
                    }
                });
            },
            // 发货
            handleShip(info) {
                this.shipList = [info];
                this.showShipPage = true;
                // 同步数据
				this.$nextTick(() => {
					this.$refs.templateRef.updateData()
				})
            },
            // 查看物流
            handleLogistics(info) {
                this.templateInfo = info;
                this.showLogisticsPage = true;
            },
             // 关闭物流
            closeLogisticsPage() {
                this.templateInfo = {};
                this.showLogisticsPage = false;
            },
            // 更新订单状态
            handleUpdateOrder(info, type) {
                let datas = {
                    orderUid: info.orderUid,
                    status: info.status
                }
                if (type !== 'close') {
                    this.updateOrders(datas);
                    return
                }

                datas.status = 4;
                this.$confirm("是否关闭该订单?", "提示", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning"
                }).then(() => {
                    this.updateOrders(datas);
				}).catch();
            },
            updateOrders(data) {
                updateOrdersStatus(data).then(result => {
                    if(result.data.isSuccessful !== "Y"){
                        this.$message.error(result.data.message);
                        return
                    }

                    this.$message.success(result.data.message);
                    // this.getData();
                    for (const item of this.dataList) {
                        if (item.orderUid === data.orderUid) {
                            Object.assign(item, result.data.data)
                            break
                        }
                    }
                }).catch(err => {});
            }
        }
    }
</script>
<style lang="scss" scoped>
   
</style>
